package com.jy.appmarket.newnetwork.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import android.annotation.SuppressLint;
import android.util.Log;

@SuppressLint("DefaultLocale")
public class CryptoUtil {
	private static final String ALGORITHM = "AES";
	public static String PRIVATE_KEY = "Takax6Ol";

	/**
	 * 加密
	 */
	@SuppressLint("TrulyRandom")
	public static String encrypt(String content, String sKey) {
		try {
			SecretKeySpec secretKey = new SecretKeySpec(sKey.getBytes(), ALGORITHM);
			Cipher cipher = Cipher.getInstance(ALGORITHM);// 创建密码器
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return parseByte2HexStr(result); // 加密
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param content
	 *            加密的数据
	 * @param sKey
	 * @return
	 */
	public static String decrypt(String content, String sKey) {
		try {
			byte[] data = parseHexStr2Byte(content);
			SecretKeySpec key = new SecretKeySpec(sKey.getBytes(), ALGORITHM);
			Cipher cipher = Cipher.getInstance(ALGORITHM);// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(data);
			return new String(result, "UTF-8"); // 解密
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 将二进制转换成16进制
	 * 
	 * @param buf
	 * @return
	 */
	private static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 将16进制转换为二进制
	 * 
	 * @param hexStr
	 * @return
	 */
	private static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

	public static void main(String[] args) {
		String pwd = "12345";
		String encryptValue = encrypt(pwd, PRIVATE_KEY);
		System.out.println("encryptValue：" + encryptValue);
		pwd = decrypt(encryptValue, PRIVATE_KEY);
		System.out.println("pwd:" + pwd);
	}

	public static String md5(String str) {
		if (str == null) {
			return null;
		}
		return md5(str, "utf-8");
	}

	private static String md5(String str, String encodingType) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		try {
			md5.update(str.getBytes(encodingType));
		} catch (UnsupportedEncodingException e) {
			md5.update(str.getBytes());
		}

		byte[] md5Bytes = md5.digest();

		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}

	public static String getFileMD5(String fileName) {
		return getFileMD5(new File(fileName));
	}

	public static String getFileMD5(File file) {
		try {
			InputStream fis = new FileInputStream(file);
			byte[] buffer = new byte[1024 * 100];
			MessageDigest md5 = MessageDigest.getInstance("Md5");
			int numRead = 0;
			while ((numRead = fis.read(buffer)) > 0) {
				md5.update(buffer, 0, numRead);
			}
			fis.close();
			return toHexString(md5.digest());
		} catch (IOException ex) {
			Log.d("CryptoUtil", "IOException", ex);
		} catch (NoSuchAlgorithmException e) {
			Log.d("CryptoUtil", "NoSuchAlgorithmException", e);
		}
		return null;
	}

	private static String toHexString(byte[] b) {
		char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
			sb.append(hexChar[b[i] & 0x0f]);
		}
		return sb.toString();
	}

}
